import json

from flask import Blueprint, render_template, request, redirect, session, url_for, jsonify
import pickle

from model.category import Category
# 导入数据表模型类
from model.question import Question
from model.member import Member
from model.carousel import Carousel
from model.db import db
from model.tag import Tag
from utils.util import md5_encrypt

# 创建蓝图
bp_home = Blueprint('home', __name__)

@bp_home.route('/')
def index():
    # 查询轮播图数据
    carousel=Carousel.query.order_by(Carousel.sort.desc()).all()
    # 获取页码
    page = request.args.get('page', 1, type=int)
    # 查询数据
    # ques=Question.query.all()
    # error_out: 页码超出范围是否报错, False表示不报错
    pagination = Question.query.paginate(page=page, per_page=10, error_out=False)
    # print(pagination.has_next, pagination.has_prev,pagination.prev_num,pagination.next_num,pagination.first,pagination.last)
    data = {
        "title": "面试宝典",
        "pagination": pagination,
        "carousel":carousel
    }
    # for que in ques:
    #     print(que.que_id,que.que_content,que.que_create_time)
    return render_template('home/index.html', **data)


@bp_home.route('/register', methods=['GET', 'POST'])
def register():
    data = {
        "title": "会员注册"
    }
    if request.method == 'GET':
        return render_template('home/register.html', **data)
    else:
        # 获取表单数据
        mem_tel = request.form.get('mem_tel')
        mem_password = request.form.get('mem_password')
        mem_confirm_password = request.form.get('mem_confirm_password')
        if mem_password != mem_confirm_password:
            data['error_confirm_password'] = '两次输入密码不一致'
            return render_template('home/register.html', **data)
        # 查询账号是否已经存在
        result = Member.query.filter_by(mem_tel=request.form['mem_tel']).first()
        if result:
            data['error_tel_repeat'] = '账号已存在,请重新输入'
            return render_template('home/register.html', **data)
        # 新增数据
        db.session.add(Member(mem_tel=mem_tel, mem_password=md5_encrypt(mem_password)))
        # 提交数据
        db.session.commit()
        # 重定向到登录页面
        return redirect(url_for('home.login'))


@bp_home.route('/login', methods=['GET', 'POST'])
def login():
    data = {
        "title": "会员登录"
    }
    if request.method == 'GET':
        return render_template('home/login.html', **data)
    else:
        #  接收表单数据
        mem_tel = request.form.get('mem_tel')
        mem_password = request.form.get('mem_password')
        # one_or_none(): 如果没有查询结果,则返回none
        # one_or_404(): 如果没有查询结果, 跳转到404错误页面
        result = Member.query.filter_by(mem_tel=mem_tel, mem_password=md5_encrypt(mem_password)).one_or_none()
        if result:
            # 从查询结果对象中删除密码信息
            if hasattr(result, 'mem_password'):
                del result.mem_password
            # pickle.dumps(): 将对象转换为字节流
            session['user_login_info'] = pickle.dumps(result)
            return redirect('/ucenter')
        else:
            data['error_account'] = '账号或密码错误'
            return render_template('home/login.html', **data)


@bp_home.route('/logout')
def logout():
    # 从session中删除登录信息
    session.pop('user_login_info', None)
    # 自动跳转到登录页面
    return redirect('/login')


@bp_home.route('/search')
def search():
    # 获取查询参数: request.args
    # print(request.args.get('keyword'),'keyword')
    keyword = request.args.get('keyword')
    result = Question.query.filter(Question.que_content.ilike(f'%{keyword}%')).all()
    data = {
        "title": "搜索",
        "keyword": keyword,
        "result": result if result else []
    }
    return render_template('home/search.html', **data)


@bp_home.route('/user/<int:id>')
def user(id):
    # 获取页码值
    page = request.args.get('page', 1, type=int)
    # questions=Question.query.filter_by(que_author_id=id).all()
    pagination = Question.query.paginate(page=page, per_page=10, error_out=False)
    member_info = Member.query.filter_by(mem_id=id).one()
    data = {"title": "个人主页", "pagination": pagination, "member_info": member_info}
    return render_template('home/user.html', **data)


@bp_home.route('/que_detail/<int:id>')
def que_detail(id):
    # 查询问题详情
    question = Question.query.filter_by(que_id=id).one_or_none()
    data = {"title": "问题详情", "question": question}
    # 更新访问次数
    if question:
        # 更新访问次数
        question.que_visit_count = question.que_visit_count + 1
        # 提交更新
        db.session.commit()
    return render_template('home/que_detail.html', **data)


@bp_home.route('/ucenter',methods=['GET','POST'])
def ucenter():
    # 查询标签信息
    tags=Tag.query.all()
    # 查询分类信息
    cates=Category.query.all()
    data = {
        "title": "会员中心",
        "tags":tags,
        "cates":cates,
        "errors":{}
    }
    # 从session中读取登录信息
    user_login_info = pickle.loads(session.get('user_login_info'))
    if not user_login_info:
        # 如果没有登录信息,则跳转到登录页面
        return redirect('/login', code=302)

    if request.method=='POST':
        # 获取登录信息
        user_login_info = pickle.loads(session.get('user_login_info'))
        post_data = {**request.form, "que_author_id": user_login_info.mem_id}
        # 获取复选框的值
        post_data['que_tags'] = json.dumps(request.form.getlist('que_tags'))

        if not post_data['que_title']:
            data['errors']['title']='请输入标题'

        if not post_data['que_cat_id']:
            data['errors']['cate']='请选择分类'

        if not post_data['que_tags']:
            data['errors']['tags']='请选择标签'

        if not post_data['que_content'].replace('<p><br></p>',''):
            data['errors']['content'] = '请输入内容'

        if data['errors']:
            return render_template('home/ucenter.html', **data)
        # 获取表单内容
        # 添加数据
        db.session.add(Question(**post_data))
        # 提交数据
        db.session.commit()

    return render_template('home/ucenter.html', **data)


# 发布话题
@bp_home.route('/post_question',methods=['POST'])
def post_question():

    # 自动重定向到会员中心页面
    return redirect(url_for('home.ucenter'))

@bp_home.route('/reset_pwd', methods=["GET", "POST"])
def reset_pwd():
    data = {
        "title": "重置密码"
    }
    if request.method == 'GET':
        return render_template('home/reset_pwd.html', **data)
    else:
        # 接收表单数据
        mem_password_old = request.values.get('mem_password_old')
        mem_password = request.values.get('mem_password')
        mem_password_confirm = request.values.get('mem_password_confirm')
        if not mem_password_old:
            data["error_password_old"] = "请输入原始密码"
        if not mem_password:
            data["error_password"] = "请输入新密码"
        if not mem_password_confirm:
            data["error_password_confirm"] = "请确认新密码"
        if mem_password != mem_password_confirm:
            data["error_password_confirm"] = "两次密码输入不一致"
        # 获取登录信息: 登录对象Member类的实例, 所以通过.访问属性
        user_login_info = pickle.loads(session.get('user_login_info'))
        if user_login_info and mem_password_old:
            # 检查原始密码是否正确
            result = Member.query.filter_by(mem_tel=user_login_info.mem_tel,
                                            mem_password=md5_encrypt(mem_password_old)).one_or_none()
            if not result:
                data["error_password_old"] = "原始密码不正确,请确认"
            else:
                # 更新密码
                result.mem_password=md5_encrypt(mem_password)
                # 提交更新
                db.session.commit()
                data['success_text']='密码更新成功'
                # 重新登录: 删除登录信息, 跳转到登录页面
                session.pop('user_login_info', None)
                return redirect(url_for('home.login'))
        return render_template('home/reset_pwd.html', **data)
